package com.huawei.esdk.tpoa.tools.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;

import com.huawei.esdk.tpoa.tools.cxf.utils.InterfaceOperationType;

public class LogAnalysis
{
    private String logName;
    private Map<String,Integer> cmdErrors = new LinkedHashMap<String,Integer>();
   
    private Map<String,List<String>> failedSiteUri = new LinkedHashMap<String,List<String>>();
    private Map<String, String> allSites = new HashMap<String, String>();
    private Map<String,String> lineCountMap = new LinkedHashMap<String,String>();
    
    private final String newSiteFlag = "New-Mailbox";
    
    private static final Logger LOGGER = Logger.getLogger(LogAnalysis.class.getName());
    
    public LogAnalysis(String logName)
    {
        this.logName = logName;
        
        File file = null;
        FileInputStream in = null;
        BufferedReader reader = null;
        try
        {

            file = new File(CreateScript.FILENAME);
            
            in = new FileInputStream(file);
            
            reader = new BufferedReader(new InputStreamReader(in, "UTF-16"));
            
            String tempStr = "";
            boolean flag = true;
            int lineCount = 1;
            while(flag)
            {
                tempStr = reader.readLine();
                if(null == tempStr)
                {
                    flag = false; 
                }
                else
                {
                    String indexFlag = "New-Mailbox -Name '";
                    int index1 = tempStr.indexOf(indexFlag);
                    if(-1 != index1)
                    {
                        String str1 = tempStr.substring(index1 + indexFlag.length());
                        String suri = str1.substring(0, str1.indexOf("'"));
                        allSites.put(String.valueOf(lineCount), suri);
                    }
                }
                
                lineCount++;
            }
        }
        catch(Exception e)
        {
            LOGGER.error(e);
        }
        finally
        {
            if (null != in)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    LOGGER.error(e);
                }
            }
            
            if (null != reader)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    LOGGER.error(e);
                }
            }
        }
    }

    
    public void analysis()
    {

        File file = null;
        FileInputStream in = null;
        BufferedReader reader = null;
        boolean flag = true;
        
        try
        {
            file = new File(logName);
            in = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
            
            StringBuffer tempStr = new StringBuffer();
            String tempStr_prev = reader.readLine();
            String tempStr_curr = null;

            while(flag)
            {
                tempStr_curr = reader.readLine();
                tempStr.setLength(0);
                tempStr.append(tempStr_prev).
                append(tempStr_curr);
                
                recordLineNum(tempStr.toString());
                
                if(null != tempStr_curr)
                {
                    tempStr_prev = tempStr_curr;
                }
                else
                {
                    flag = false;
                }
            }
        }
        catch(IOException e)
        {
            LOGGER.error(e);
            flag = false;
        }
        finally
        {
            try
            {
                if(null != reader)
                {
                    reader.close();
                }
                if(null != in)
                {
                    in.close();
                }
            }
            catch (IOException e)
            {
                LOGGER.error(e);
            }
        }
        
        analysisRecordLineNumMap();
        
        showResult();
        
 
    }

    private void recordLineNum(String str)
    {
        String flag = CreateScript.FILENAME + ":";
        int index  = str.indexOf(flag);
        if(-1 != index)
        {
            if(index + flag.length() < str.length())
            {
                String str1 = str.substring(index + flag.length());
                int index1 = str1.indexOf(" ");
                if(-1 != index1){
                    String suri = str1.substring(0, index1);
                    lineCountMap.put(suri, suri);
                }
            }
        }
    }
    
    private void analysisRecordLineNumMap()
    {
        cmdErrors.put(newSiteFlag, 0);

        List<String> uris1 = new ArrayList<String>();
        failedSiteUri.put(newSiteFlag, uris1);
        
        for(Entry<String, String> item : lineCountMap.entrySet())
        {
            if(allSites.containsKey(item.getKey()))
            {
                Integer size = cmdErrors.get(newSiteFlag) + 1;
                cmdErrors.put(newSiteFlag, size);
                failedSiteUri.get(newSiteFlag).add(allSites.get(item.getKey()));
            }
        }

    }
 
    private void showResult()
    {

        Map<String, String> map = System.getenv();
        String computeruserName = map.get("USERNAME");
        
        StringBuffer sb1 = new StringBuffer();
        sb1.append(InterfaceOperationType.ADD.toString()).append(" | ");
        sb1.append("Create Room Resource").append(" | ");
        sb1.append(computeruserName).append("\n");
        
        for(Entry<String, Integer> entry : cmdErrors.entrySet())
        {
            if(entry.getKey().equals(newSiteFlag))
            {
                
                List<String> failedSites = failedSiteUri.get(newSiteFlag);
                
                Map<String, String> sccessSitesMap = new LinkedHashMap<String, String>();
                for(Entry<String, String> item : allSites.entrySet())
                {
                    sccessSitesMap.put(item.getValue(), item.getValue());
                }
                
                if(null != failedSites && 0 < failedSites.size())
                {
                    sb1.append(entry.getValue() +
                        " Outlook room resources fail to be created");
                    sb1.append(",the details are as follows:").append("\n");
                    for(String uri : failedSites)
                    {
                        sb1.append(uri).append("\n");;
                        sccessSitesMap.remove(uri);
                    }
                }
                else
                {
                    sb1.append("No Outlook room resources fails to be created").append("\n"); 
                }
                
                if(null != sccessSitesMap && 0 < sccessSitesMap.size())
                {
                    sb1.append(sccessSitesMap.size() + " Outlook room resources are created");
                    sb1.append(",the details are as follows:").append("\n");
                    for(String uri : sccessSitesMap.keySet())
                    {
                        sb1.append(uri).append("\n");
                    }
                }
                else
                {
                    sb1.append("No Outlook room resources is created").append("\n");
                }
            }
        }
        LOGGER.info(sb1.toString());
    }
    
    public static void main(String[] args) throws IOException
    {
        args = new String[]{
            "Exchange_Management_Shell_Log.txt"
        };
        if(args.length > 0 && null != args[0])
        {
            LogAnalysis logAnalysis = new LogAnalysis(args[0]);
            LOGGER.info("Execution of the powershell script is successful.");
            logAnalysis.analysis();
            LOGGER.info("More Info please see " + logAnalysis.logName);
        }
    }
}
